/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.krossk.dao;

import br.com.krossk.jpa.JPAFactory;
import br.com.krossk.model.Usuario;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

/**
 *
 * @author Henrique
 */
public class UsuarioDAO {

    private static UsuarioDAO instance = new UsuarioDAO();

    public static UsuarioDAO getInstance(){
        return instance;
    }

    public List <Usuario> getAll(){
        EntityManager em = JPAFactory.getEntityManager();
        try{
            Query query = em.createNamedQuery("Usuario.findAll");
            return query.getResultList();
        }finally{
            em.close();
        }
    }

    public Usuario getById(int idUsuario){
        EntityManager em = JPAFactory.getEntityManager();
        try{
            return em.find(Usuario.class, idUsuario);
        }finally{
            em.close();
        }

    }

    public void save(Usuario a){
        EntityManager em = JPAFactory.getEntityManager();
        try{
            em.getTransaction().begin();
            em.persist(a);
            em.getTransaction().commit();
        }finally{
            em.close();
        }
    }

    public void delete(int idUsuario){
        EntityManager em = JPAFactory.getEntityManager();
        try{
            Usuario a = em.find(Usuario.class, idUsuario);
            em.getTransaction().begin();
            em.remove(a);
            em.getTransaction().commit();
        }finally{
            em.close();
        }
    }

    public Usuario getByEmail(String email){
        EntityManager em = JPAFactory.getEntityManager();
        try{
            Query query = em.createNamedQuery("Usuario.findByEmail");
            query.setParameter("email", email);
            return (Usuario)query.getSingleResult();
        }catch(NoResultException e)
        {
            return null;
        }
        finally{
            em.close();
        }
    }

    public void update(Usuario u){
        EntityManager em =JPAFactory.getEntityManager();
        em.getTransaction().begin();
        em.merge(u);
        em.getTransaction().commit();
        em.close();
    }
}
